//
//  HomePageViewController.m
//  FeiYang
//
//  Created by User on 15/10/10.
//  Copyright © 2015年 feiyang. All rights reserved.
//
#import "ImagePlayerView.h"
#import "HomePageViewController.h"
#import "NewModel.h"
#import "BannerModel.h"
#import "NewsDetailViewController.h"

@interface HomePageViewController ()<UITableViewDataSource,UITableViewDelegate,ImagePlayerViewDelegate>
@property (nonatomic,strong)UITableView * mainTableView;
@property (nonatomic,strong)NSMutableArray     * dataSourceArray;//新闻列表数据源
@property (nonatomic,strong)NSMutableArray     * bannerDataSource;//轮播图数据源
@property (nonatomic,strong)ImagePlayerView    * banner;//轮播图
@property (nonatomic, assign)int idx;
@property (nonatomic,assign) int n;
@property (nonatomic,strong)UIView *noDataView;
@property (nonatomic,strong)UIView *noNet;
@end

@implementation HomePageViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor hexStringToColor:@"#f3f3f3"];
    [self createTheNavigationBar];
    [self createTheUi];
    [self refreshTheBanner];
}
-(void)createTheNavigationBar
{
    TopView *topView = [[TopView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_HEIGHT, 64.0f)];
    [topView setTitile:@"大大理财"];
    [self.view addSubview:topView];
}
-(void)createTheUi
{
    _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64-49) style:UITableViewStylePlain];
    _mainTableView.dataSource = self;
    _mainTableView.delegate = self;
    _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _mainTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    _mainTableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTheTableView)];
    [self createTheBanner];//创建轮播图
    [self.view addSubview:_mainTableView];
    [self.mainTableView addSubview:self.noDataView];
    [self.mainTableView addSubview:self.noNet];
    [_mainTableView.header beginRefreshing];
}
#pragma mark --------------表的刷新与加载更多
-(void)refreshTheTableView
{
    _idx = 0;
    _n = 0;
    
    [self getHttpData];
    [self refreshTheBanner];
}
- (void)AddtoTheProjectTableView
{
    [self getHttpData];
}
- (void)getHttpData
{
    _noDataView.hidden = TRUE;
    _noNet.hidden = TRUE;
    
    if (!_dataSourceArray) {
        _dataSourceArray = [NSMutableArray array];
    }
    _n++;
    
    NSDictionary * dict = @{@"page.size":[NSNumber numberWithInt:10],@"page.pn":[NSNumber numberWithInt:_idx + 1]};

    [AppGlobalClass PostDataWithNSstring:GETNEWSLIST withDictionary:dict success:^(NSDictionary *dictionary){
        
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            [self.mainTableView.header endRefreshing];
            [self.mainTableView.footer setState:MJRefreshStateIdle];
            [self.mainTableView.footer endRefreshing];
            
            if(_idx == 0)
            {
                [_dataSourceArray removeAllObjects];
            }
            
            NSArray *dataArray = [dictionary objectForKey:@"responseData"];
            NSDictionary *dataDict = [dataArray firstObject];
            
            if([[dataDict objectForKey:@"pages"] intValue] > _idx)
            {
                
                NSMutableArray *listArray = [[[dictionary objectForKey:@"responseData"]firstObject] objectForKey:@"rows"];
                
                for(int i = 0; i < listArray.count; i++)
                {
                    NSDictionary * modelDict = listArray[i];
                    NewModel * model = [[NewModel alloc]init];
                    [model setValuesForKeysWithDictionary:modelDict];
                    [_dataSourceArray addObject:model];
                }
                
                _idx++;
                
                [self.mainTableView reloadData];
                
                if(_dataSourceArray.count < 10)
                {
                    [self.mainTableView.footer endRefreshingWithNoMoreData];
                }
                else
                {
                    if (_n<2) {
                        
                        self.mainTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(AddtoTheProjectTableView)];
                        
                    }
                    
                }
            }
            else
            {
                if (self.dataSourceArray.count==0) {
                    
                    //                    无数据
                    self.noDataView.hidden = FALSE;
                    
                }
                
                [self.mainTableView.footer endRefreshingWithNoMoreData];
            }
            
            
        }else
        {
            //没有真确返回
            [self.dataSourceArray removeAllObjects];
            [_mainTableView reloadData];
            _noDataView.hidden = FALSE;
            
            [self.mainTableView.header endRefreshing];
            [self.mainTableView.footer setState:MJRefreshStateIdle];
            [self.mainTableView.footer endRefreshing];
        }
        
        
        
    } failure:^(NSError *error){
        [self.mainTableView.header endRefreshing];
        [self.mainTableView.footer setState:MJRefreshStateIdle];
        [self.mainTableView.footer endRefreshing];
        //     无数据
        _noDataView.hidden = FALSE;
        [_dataSourceArray removeAllObjects];
        [self.mainTableView reloadData];
    } networkerror:^(NSString *networkerror){
        [self.mainTableView.header endRefreshing];
        [self.mainTableView.footer setState:MJRefreshStateIdle];
        [self.mainTableView.footer endRefreshing];
        _noNet.hidden = FALSE;
        [_dataSourceArray removeAllObjects];
        [self.mainTableView reloadData];
        //       无网络图标
    }];
}
//没网提示
#pragma mark - 无网提示
#pragma mark - 没网提示
-(UIView *)noNet
{
    if (!_noNet) {
        _noNet = [[UIView alloc]initWithFrame:CGRectMake((SCREEN_WIDTH - 200.0f) / 2.0f, (SCREEN_HEIGHT - 200.0f-64+100) / 2.0f, 116.0f, 130.0f)];
        _noNet.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 200, 200);
        [button setImage:[UIImage imageNamed:@"img_nonetwork"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonAgainTapped:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 40, 200, 44)];
        label.text = @"网络不通\n点击重新搜索";
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        label.font = [UIFont systemFontOfSize:14.0f];
        
        label.textColor = [UIColor colorWithWhite:0.000 alpha:0.540];
        [_noNet addSubview:label];
        [_noNet addSubview:button];
    }
    return _noNet;
}

-(UIView *)noDataView{
    if (!_noDataView) {
        
        _noDataView = [[UIView alloc]initWithFrame:CGRectMake((SCREEN_WIDTH - 200.0f) / 2.0f, (SCREEN_HEIGHT - 200.0f-64+100) / 2.0f, 200.0f, 200.0f)];
        _noDataView.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 200, 200);
        [button setImage:[UIImage imageNamed:@"img_nodata"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonAgainTapped:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 40, 200, 44)];
        label.text = @"暂无数据\n点击重新搜索";
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        label.font = [UIFont systemFontOfSize:14.0f];
        
        label.textColor = [UIColor colorWithWhite:0.000 alpha:0.540];
        [_noDataView addSubview:label];
        [_noDataView addSubview:button];
    }
    
    return _noDataView;
}
- (void)buttonAgainTapped:(id)sender
{
    [self.mainTableView.header beginRefreshing];
}

#pragma mark-----------dataSource和delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSourceArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellId = @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
        UILabel * title = [[UILabel alloc]initWithFrame:CGRectMake(92, 16, SCREEN_WIDTH - 108, 20)];
        title.textColor = [UIColor hexStringToColor:@"#5A5A5A"];
        title.tag = 101;
        title.font = [UIFont boldSystemFontOfSize:14];
        [cell addSubview:title];
        
        UILabel * detailabel = [[UILabel alloc]initWithFrame:CGRectMake(92, 40, SCREEN_WIDTH - 108, 42)];
        detailabel.numberOfLines = 0;
        detailabel.tag = 102;
        detailabel.textColor = [UIColor hexStringToColor:@"#969494"];
        detailabel.font = [UIFont systemFontOfSize:12];
        [cell addSubview:detailabel];
        
        
        UIView * imageBackView = [[UIView alloc]initWithFrame:CGRectMake(16, 16, 60, 60)];
        imageBackView.layer.borderWidth = 0.5;
        imageBackView.layer.masksToBounds = TRUE;
        imageBackView.layer.borderColor = [[UIColor blackColor]CGColor];
        [cell addSubview:imageBackView];
        
        UIImageView * newsImageView = [[UIImageView alloc]initWithFrame:CGRectMake(16+4 , 16+4 , 52, 52)];
        newsImageView.tag = 103;
        newsImageView.clipsToBounds = TRUE;
        newsImageView.contentMode = UIViewContentModeScaleAspectFill;
        [cell addSubview:newsImageView];
        
        UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(8, 91.5, SCREEN_WIDTH - 16, 0.5)];
        lineView.backgroundColor = [UIColor hexStringToColor:kColorGraySperator];
        [cell addSubview:lineView];
        
    }
    if (_dataSourceArray.count >0)
    {
        NewModel * model = _dataSourceArray[indexPath.row];
        UILabel * title = (UILabel *)[cell viewWithTag:101];
        title.text = [NSString stringWithFormat:@"%@",model.title];
        
        UILabel * detail = (UILabel *)[cell viewWithTag:102];
        detail.text = [NSString stringWithFormat:@"%@",model.contentV];
        
        UIImageView * newsImageView = (UIImageView *)[cell viewWithTag:103];
        NSString * urlString = [NSString stringWithFormat:@"%@%@",IMAGE_URL_TEST,model.showImage];
        newsImageView.contentMode = UIViewContentModeCenter;
        [newsImageView sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:[UIImage imageNamed:@"img_default"] options:SDWebImageRetryFailed completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            newsImageView.contentMode = UIViewContentModeScaleAspectFill;
            newsImageView.clipsToBounds = TRUE;
        }];
        
    }
   
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewModel * model = _dataSourceArray[indexPath.row];
    NewsDetailViewController * vc = [[NewsDetailViewController alloc]initWithNewsId:[NSString stringWithFormat:@"%@",model.newsId]];
    [self.navigationController pushViewController:vc animated:TRUE];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 92;
}
#pragma mark------------------轮播图
-(void)createTheBanner
{
    _banner = [[ImagePlayerView alloc]init];
    _banner.frame = CGRectMake(0, 0, SCREEN_WIDTH, 180);
    _banner.imagePlayerViewDelegate = self;
    _banner.scrollInterval = 3.0f;
    _banner.pageControlPosition = ICPageControlPosition_BottomCenter;
    _banner.hidePageControl = FALSE;
    _mainTableView.tableHeaderView = _banner;
    
}
-(NSInteger)numberOfItems
{
    if (_bannerDataSource.count == 0) {
        return 1;
    }
    return _bannerDataSource.count;
}
- (void)imagePlayerView:(ImagePlayerView *)imagePlayerView loadImageForImageView:(UIImageView *)imageView index:(NSInteger)index
{
    if (_bannerDataSource.count>0)
    {
        imagePlayerView.autoScroll = TRUE;
        imagePlayerView.hidePageControl = FALSE;
        imageView.contentMode = UIViewContentModeCenter;
        BannerModel * model = _bannerDataSource[index];
        [imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMAGE_URL_TEST,model.cover]] placeholderImage:[UIImage imageNamed:@"img_default"] options:SDWebImageRetryFailed completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            imageView.clipsToBounds = TRUE;
            imageView.contentMode = UIViewContentModeScaleAspectFill;
        }];
        
    }else
    {
        [imagePlayerView stopTimer];
        imagePlayerView.hidePageControl = TRUE;
    [imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMAGE_URL_TEST,@"111"]] placeholderImage:[UIImage imageNamed:@"img_default"] options:SDWebImageRetryFailed];
        imageView.contentMode = UIViewContentModeCenter;
        imageView.backgroundColor = [UIColor hexStringToColor:@"#E5E5E5"];
    }
}
-(void)imagePlayerView:(ImagePlayerView *)imagePlayerView didTapAtIndex:(NSInteger)index
{
    BannerModel * model = _bannerDataSource[index];
    NewsDetailViewController * vc = [[NewsDetailViewController alloc]initWithNewsId:[NSString stringWithFormat:@"%@",model.newsId]];
    [self.navigationController pushViewController:vc animated:TRUE];
}
#pragma mark-------------------轮播图网络请求
-(void)refreshTheBanner
{
    if (!_bannerDataSource)
    {
        _bannerDataSource = [NSMutableArray array];
    }
    [_bannerDataSource removeAllObjects];
    [AppGlobalClass PostDataWithNSstring:GETCAROUSENEWSLIST withDictionary:nil success:^(NSDictionary *dictionary) {
          if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
          {
              NSArray *listArray = [[[dictionary objectForKey:@"responseData"]firstObject] objectForKey:@"rows"];
              for (NSDictionary * dic in listArray)
              {
                  BannerModel * model = [[BannerModel alloc]init];
                  [model setValuesForKeysWithDictionary:dic];
                  [_bannerDataSource addObject:model];
              }
              [_banner reloadData];
              
          }
    } failure:^(NSError *error) {
         [_banner reloadData];
    } networkerror:^(NSString *networkerror) {
         [_banner reloadData];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
